#include "ball.h"
#include "time.h"
static const double pi = 3.14159265358979323846;

ball::ball(int width, int height)
{
	x = height/2;
	y = width/2;
	this->width = width;
	this->height = height;
	radius = 8;
	xspeed = 15;
	yspeed = 15;
	srand(time(NULL));
	angle = rand() % 360;
	HitLeft = false;
	HitRight = false;
	
}

void ball::init(int x,int y, int a) {
	this->y=y;
	this->x=x;
	angle=a;
}
void ball::calculateDisplacementX(int angle, int speed)
{
	this->displacementX = (cos(pi * angle / 180) * speed);
}

void ball::calculateDisplacementY(int angle, int speed)
{
	this->displacementY = (sin(pi * angle / 180) * speed);
}

void ball::updatePositionandDraw(IplImage* img)
{
	
	if (x + radius >= width)
	{
		
		y = height/2;
		x = width/2;
        HitRight = true;
		if (rand()%2 ==0){
		xspeed = rand()%7 + 10;
		yspeed = rand()%7 + 10;
		}
		else {
			xspeed = -(rand()%7 + 8);
			yspeed = -(rand()%7 + 8);
	}
	}
	if (x - radius <= 0)
	{
		
		y = height/2;
		x = width/2;
	    HitLeft = true;
	    if (rand()%2 == 0){
		xspeed = rand()%7 + 8;
		yspeed = rand()%7 + 8;
		}
		else {
			xspeed = -(rand()%7 + 8);
			yspeed = -(rand()%7 + 8);
		}
	}
	if (y + radius >= height)
	    yspeed = -yspeed;
	if (y - radius  <= 0)
	    yspeed = -yspeed;

	
	x += xspeed;
	y -= yspeed;

	cvDrawCircle(img, cvPoint(x,y), radius, CV_RGB(255, 0, 0), -1);
	cvDrawCircle(img, cvPoint(x,y), radius, CV_RGB(0, 0, 0));
	
}

void ball::bounce()
{
	xspeed = -xspeed;
	


}

bool ball::isHitLeft()
{
    bool temp = HitLeft;
    HitLeft = false;
    return temp;
}
bool ball::isHitRight()
{
    bool hit = HitRight;
    HitRight = false;
    return hit;
}
int ball::getY() const {
	return y;
}
int ball::getX() const {
	return x;
}

int ball::getR() const {
	return radius;
}



